package com.cps116.friendstracker;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.cps116.resource.HttpResponseDecoder;
import com.easy.facebook.android.apicall.FQL;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

public class QueryActivity_FriendsWithinDistanceActivity extends BaseActivity {
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.queryactivity_friendswithindistanceactivity_layout);
	

		Spinner findFriendsWithinDistanceOptionSpinner = (Spinner) findViewById(R.id.queryview_friendswithindistanceactivity_spinner);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.queryview_friendswithindistance_array, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		findFriendsWithinDistanceOptionSpinner.setAdapter(adapter);
		findFriendsWithinDistanceOptionSpinner.setOnItemSelectedListener(new UpdateOptionListener(this));

		
		
	}

	protected void QueryDistance(String distance)
	{
		try {
			ArrayList<String> friends = (ArrayList<String>)((FriendsTrackerApplication) getApplication()).getUser().getFriends();
			String friend_list = "";
			for(String friend: friends)
			{
				friend = friend.split(",")[1];
				friend_list = friend_list+";"+friend;
			}
			friend_list = friend_list.substring(1);

			FQL facebookFQL = ((FriendsTrackerApplication) getApplication()).getFacebookFQL();
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost("http://dbcourse.cs.duke.edu/tnd6/FFQueries/friendsindistance.php");

			// Add your data
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
			nameValuePairs.add(new BasicNameValuePair("userid", ((FriendsTrackerApplication) this.getApplication()).getFacebookUserId()));
			nameValuePairs.add(new BasicNameValuePair("time", new Date().toString()));
			nameValuePairs.add(new BasicNameValuePair("friends", friend_list));
			nameValuePairs.add(new BasicNameValuePair("distance", distance));
			
			httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

			// Execute HTTP Post Request
			HttpResponse response = httpclient.execute(httppost);
			
			//uid;road;distance;...
			String[] results = HttpResponseDecoder.getResponseBody(response).split(";");
			List<String> friendIds = new ArrayList<String>(results.length/3);
			List<String> friendLocations = new ArrayList<String>(results.length/3);
			List<String> friendDistances = new ArrayList<String>(results.length/3);
			for(int i=0; i<results.length; i++)
			{
				if(i%3 == 0)
					friendIds.add(results[i]);
				else if(i%3 == 1)
					friendLocations.add(results[i]);
				else
					friendDistances.add(results[i]);
			}
			
			//convert friend id to name
			String[] listView;
			if(results.length == 1)
			{
				listView = new String[1];
				listView[0] = "No friends within distance.";
			}
			else
			{
				listView = new String[friendIds.size()];
				for(int i=0; i<friendIds.size(); i++)
				{				
					String xmlStr = facebookFQL.fqlQuery("select name from user where uid = "+friendIds.get(i));
					Pattern p = Pattern.compile("<name>(.+?)</name>");
					Matcher m = p.matcher(xmlStr);
					String name = "Name not found";
					if(m.find())
					{
						name = m.group(1);
					}

					listView[i] = name+ " - " + friendLocations.get(i) + " - " + friendDistances.get(i).substring(0,friendDistances.get(i).indexOf('.')+3) + " mi.";
				}
			}
			ListView distanceList=(ListView)findViewById(R.id.query_activity_friends_in_distance_listview);
			ArrayAdapter<String> distance_adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listView);
			distanceList.setAdapter(distance_adapter);
			
		} catch (Exception e) {
			//return "service failed";
		}
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	
	private class UpdateOptionListener implements OnItemSelectedListener {

		Activity activityCaller;

		public UpdateOptionListener(QueryActivity_FriendsWithinDistanceActivity activity) {
			activityCaller = activity;
		}

		public void onItemSelected(AdapterView<?> parent, View view, int index,
				long arg3) {

			String distance_choice = parent.getItemAtPosition(index)
					.toString();
			
			distance_choice = distance_choice.substring(0,distance_choice.indexOf(" "));
			
			QueryDistance(distance_choice);

			/*// display the message that you have updated
			Toast.makeText(parent.getContext(),
					String.format("Current update time: %s", user_time_choice),
					Toast.LENGTH_LONG).show();

			// get the time intervals for update in milliseconds
			long user_time_milliseconds = timeConverter.get(user_time_choice)
					.longValue();
			// Log.d("ProfileActivity", "" + user_time_milliseconds);

			// convert the user_time_choice to string
			((FriendsTrackerApplication) getApplication())
					.startNewUserLocationUpdateServiceInterval(activityCaller,
							user_time_milliseconds);*/
		}

		public void onNothingSelected(AdapterView<?> view) {
			// do not change anything
		}
	}

	
}

